from django.http import JsonResponse
from django.http import JsonResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework import status
# 从Django的认证模块中导入密码哈希处理函数
# make_password: 用于将明文密码转换为加密哈希值
# check_password: 用于验证明文密码与已加密密码哈希值是否匹配
from django.contrib.auth.hashers import make_password, check_password
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from django.conf import settings
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import Q
import os
import uuid
import base64
from datetime import datetime

from .models import SysUser
from role.models import SysRole, SysUserRole
from .permissions import get_accessible_users, get_user_with_roles, can_manage_user, can_create_user_with_role, is_super_admin, is_admin, get_user_role_names
from rest_framework_simplejwt.settings import api_settings
# 用于处理JWT（JSON Web Token）的刷新令牌功能。
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework.permissions import AllowAny


def get_tokens_for_user(user):
    """
    为指定用户生成JWT令牌
    该函数使用Django REST framework的JWT功能为用户生成刷新令牌和访问令牌，
    用于用户的认证和授权。
    参数:
        user: 用户对象，通常为Django的User模型实例
    返回值:
        str: 访问令牌字符串，用于API请求的认证
    """
    # 为用户生成刷新令牌
    refresh = RefreshToken.for_user(user)
    print(f"Generated token for user {user.username}: {refresh.access_token}")
    # 返回访问令牌字符串
    return str(refresh.access_token)


class LoginView(APIView):
    """
    用户登录视图类
    处理用户登录请求
    """
    permission_classes = [AllowAny]  # 允许任何用户访问

    def post(self, request):
        """
        处理POST登录请求
        :param request: 包含用户名和密码的请求
        :return: 包含JWT令牌的用户信息或错误信息
        """
        # 获取请求数据 - 处理JSON数据
        import json
        if hasattr(request, 'data'):
            # DRF请求
            request_data = request.data
        else:
            # Django原生请求
            if request.content_type == 'application/json':
                request_data = json.loads(request.body.decode('utf-8'))
            else:
                request_data = request.POST
                
        username = request_data.get('username')  # 获取用户名
        password = request_data.get('password')  # 获取密码

        if not username or not password:
            return Response({
                'code': 400,
                'message': '用户名和密码不能为空'
            }, status=status.HTTP_400_BAD_REQUEST)

        try:
            user = SysUser.objects.get(username=username)  # 根据用户名获取用户对象

            # 检查用户状态
            if user.status == 1:
                return Response({
                    'code': 403,
                    'message': '账号已被停用'
                }, status=status.HTTP_403_FORBIDDEN)

            # 验证密码
            if check_password(password, user.password):
                # 更新最后登录时间
                user.login_date = datetime.now().date()
                user.save()  # 保存用户信息

                # 生成JWT令牌
                token = get_tokens_for_user(user)

                return Response({
                    'code': 200,
                    'message': '登录成功',
                    'data': {
                        'token': token,
                        'user': {
                            'id': user.id,
                            'username': user.username,
                            'email': user.email,
                            'avatar': user.avatar,
                            'phonenumber': user.phonenumber
                        }
                    }
                })
            else:
                return Response({
                    'code': 401,
                    'message': '密码错误'
                }, status=status.HTTP_401_UNAUTHORIZED)

        except SysUser.DoesNotExist:
            return Response({
                'code': 404,
                'message': '用户不存在'
            }, status=status.HTTP_404_NOT_FOUND)


class RegisterView(APIView):
    """
    用户注册视图类
    处理用户注册请求
    """
    permission_classes = [AllowAny]  # 允许任何用户访问

    def post(self, request):
        """
        处理POST注册请求
        :param request: 包含用户注册信息的请求
        :return: 注册成功信息或错误信息
        """
        # 获取请求数据 - 处理JSON数据
        import json
        if hasattr(request, 'data'):
            # DRF请求
            request_data = request.data
        else:
            # Django原生请求
            if request.content_type == 'application/json':
                request_data = json.loads(request.body.decode('utf-8'))
            else:
                request_data = request.POST
                
        username = request_data.get('username')
        password = request_data.get('password')
        email = request_data.get('email', '')
        phonenumber = request_data.get('phonenumber', '')

        if not username or not password:
            return Response({
                'code': 400,
                'message': '用户名和密码不能为空'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 检查用户名是否已存在
        if SysUser.objects.filter(username=username).exists():
            return Response({
                'code': 400,
                'message': '用户名已存在'
            })

        try:
            # 创建新用户
            user = SysUser.objects.create(
                username=username,
                password=make_password(password),  # 对密码进行加密处理
                email=email,
                phonenumber=phonenumber,
                status=0,  # 默认正常状态
            )

            # 为新注册用户分配默认角色（普通用户）
            from role.models import SysRole, SysUserRole
            try:
                # 获取普通用户角色
                default_role = SysRole.objects.get(name='普通用户')
                # 创建用户角色关联
                SysUserRole.objects.create(user_id=user.id, role=default_role)
            except SysRole.DoesNotExist:
                # 如果普通用户角色不存在，则创建该角色
                default_role = SysRole.objects.create(
                    name='普通用户',
                    description='普通用户角色',
                    status=0
                )
                SysUserRole.objects.create(user_id=user.id, role=default_role)

            # 获取用户角色信息
            from user.permissions import get_user_role_names
            user_roles = get_user_role_names(user.id)

            return Response({
                'code': 200,
                'message': '注册成功',
                'data': {
                    'id': user.id,
                    'username': user.username,
                    'email': user.email,
                    'roles': user_roles,
                    'role_display': ', '.join(user_roles) if user_roles else '无角色'
                }
            })

        except Exception as e:
            return Response({
                'code': 500,
                'message': f'注册失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class LogoutView(APIView):
    """
    用户登出视图类
    处理用户登出请求
    """

    def post(self, request):
        """
        处理POST登出请求
        :param request: 包含JWT令牌的请求
        :return: 登出成功信息
        """
        return Response({
            'code': 200,
            'message': '登出成功'
        })


class UserInfoView(APIView):
    """
    获取用户信息视图类
    根据JWT令牌获取用户信息
    """
    # 移除DRF认证要求，使用中间件认证
    permission_classes = [AllowAny]

    def get(self, request):
        """
        处理GET请求获取用户信息
        :param request: 包含JWT令牌的请求
        :return: 用户信息
        """
        try:
            # 检查中间件是否已设置用户
            if hasattr(request, '_jwt_user'):
                user = request._jwt_user
            else:
                # 如果中间件没有设置用户，手动验证JWT
                auth_header = request.META.get('HTTP_AUTHORIZATION')
                if not auth_header or not auth_header.startswith('Bearer '):
                    return Response({
                        'code': 401,
                        'message': '缺少认证令牌'
                    }, status=status.HTTP_401_UNAUTHORIZED)
                
                from rest_framework_simplejwt.tokens import AccessToken
                token_str = auth_header.split(' ')[1]
                access_token = AccessToken(token_str)
                user_id = access_token['user_id']
                
                if isinstance(user_id, str):
                    user_id = int(user_id)
                
                user = SysUser.objects.get(id=user_id)
            
            if user and hasattr(user, 'id'):
                return Response({
                    'code': 200,
                    'message': '获取用户信息成功',
                    'data': {
                        'id': user.id,
                        'username': user.username,
                        'email': user.email,
                        'avatar': user.avatar,
                        'phonenumber': user.phonenumber,
                        'nickname': user.nickname,
                        'gender': user.gender,
                        'birthday': user.birthday.strftime('%Y-%m-%d') if user.birthday else None,
                        'bio': user.bio
                    }
                })
            else:
                return Response({
                    'code': 401,
                    'message': '未授权访问'
                }, status=status.HTTP_401_UNAUTHORIZED)
        except SysUser.DoesNotExist:
            return Response({
                'code': 401,
                'message': '用户不存在'
            }, status=status.HTTP_401_UNAUTHORIZED)
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'获取用户信息失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class UpdateProfileView(APIView):
    """
    更新个人信息视图类
    处理用户个人信息更新请求
    """
    permission_classes = [AllowAny]

    def put(self, request):
        """
        处理PUT请求更新用户个人信息
        :param request: 包含用户信息的请求
        :return: 更新结果
        """
        try:
            # 获取请求数据 - 处理JSON数据
            import json
            if hasattr(request, 'data'):
                # DRF请求
                data = request.data
            else:
                # Django原生请求
                if request.content_type == 'application/json':
                    data = json.loads(request.body.decode('utf-8'))
                else:
                    data = request.POST
            
            # 获取当前用户
            user = None
            if hasattr(request, '_jwt_user'):
                user = request._jwt_user
            else:
                # 手动验证JWT
                auth_header = request.META.get('HTTP_AUTHORIZATION')
                if not auth_header or not auth_header.startswith('Bearer '):
                    return Response({
                        'code': 401,
                        'message': '缺少认证令牌'
                    }, status=status.HTTP_401_UNAUTHORIZED)
                
                from rest_framework_simplejwt.tokens import AccessToken
                token_str = auth_header.split(' ')[1]
                access_token = AccessToken(token_str)
                user_id = access_token['user_id']
                
                if isinstance(user_id, str):
                    user_id = int(user_id)
                
                user = SysUser.objects.get(id=user_id)

            # 更新允许的字段
            allowed_fields = ['email', 'phonenumber', 'nickname', 'gender', 'birthday', 'bio']
            
            for field in allowed_fields:
                if field in data:
                    if field == 'birthday' and data[field]:
                        # 处理日期格式
                        try:
                            birthday_date = datetime.strptime(data[field], '%Y-%m-%d').date()
                            setattr(user, field, birthday_date)
                        except ValueError as ve:
                            return Response({
                                'code': 400,
                                'message': '日期格式错误，请使用YYYY-MM-DD格式'
                            }, status=status.HTTP_400_BAD_REQUEST)
                    else:
                        setattr(user, field, data[field])
            
            # 保存更新
            user.save()
            
            return Response({
                'code': 200,
                'message': '个人信息更新成功',
                'data': {
                    'id': user.id,
                    'username': user.username,
                    'email': user.email,
                    'avatar': user.avatar,
                    'phonenumber': user.phonenumber,
                    'nickname': user.nickname,
                    'gender': user.gender,
                    'birthday': user.birthday.strftime('%Y-%m-%d') if user.birthday else None,
                    'bio': user.bio
                }
            })
            
        except SysUser.DoesNotExist as e:
            return Response({
                'code': 401,
                'message': '用户不存在'
            }, status=status.HTTP_401_UNAUTHORIZED)
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'更新失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class ChangePasswordView(APIView):
    """
    修改密码视图类
    处理用户密码修改请求
    """
    permission_classes = [AllowAny]

    def put(self, request):
        """
        处理PUT请求修改用户密码
        :param request: 包含密码信息的请求
        :return: 修改结果
        """
        try:
            # 获取当前用户
            if hasattr(request, '_jwt_user'):
                user = request._jwt_user
            else:
                # 手动验证JWT
                auth_header = request.META.get('HTTP_AUTHORIZATION')
                if not auth_header or not auth_header.startswith('Bearer '):
                    return Response({
                        'code': 401,
                        'message': '缺少认证令牌'
                    }, status=status.HTTP_401_UNAUTHORIZED)
                
                from rest_framework_simplejwt.tokens import AccessToken
                token_str = auth_header.split(' ')[1]
                access_token = AccessToken(token_str)
                user_id = access_token['user_id']
                
                if isinstance(user_id, str):
                    user_id = int(user_id)
                
                user = SysUser.objects.get(id=user_id)

            # 获取请求数据 - 处理JSON数据
            import json
            if hasattr(request, 'data'):
                # DRF请求
                request_data = request.data
            else:
                # Django原生请求
                if request.content_type == 'application/json':
                    request_data = json.loads(request.body.decode('utf-8'))
                else:
                    request_data = request.POST
                    
            old_password = request_data.get('oldPassword')
            new_password = request_data.get('newPassword')
            confirm_password = request_data.get('confirmPassword')
            
            # 数据验证
            if not old_password or not new_password or not confirm_password:
                return Response({
                    'code': 400,
                    'message': '密码信息不能为空'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            if new_password != confirm_password:
                return Response({
                    'code': 400,
                    'message': '两次输入的密码不一致'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            if len(new_password) < 6:
                return Response({
                    'code': 400,
                    'message': '密码长度不能少于6位'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 验证原密码
            if not check_password(old_password, user.password):
                return Response({
                    'code': 400,
                    'message': '原密码错误'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 更新密码
            user.password = make_password(new_password)
            user.save()
            
            return Response({
                'code': 200,
                'message': '密码修改成功'
            })
            
        except SysUser.DoesNotExist:
            return Response({
                'code': 401,
                'message': '用户不存在'
            }, status=status.HTTP_401_UNAUTHORIZED)
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'密码修改失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class UploadAvatarView(APIView):
    """
    头像上传视图类
    处理用户头像上传请求
    """
    permission_classes = [AllowAny]

    def post(self, request):
        """
        处理POST请求上传用户头像
        :param request: 包含头像数据的请求
        :return: 上传结果
        """
        try:
            # 获取当前用户
            if hasattr(request, '_jwt_user'):
                user = request._jwt_user
            else:
                # 手动验证JWT
                auth_header = request.META.get('HTTP_AUTHORIZATION')
                if not auth_header or not auth_header.startswith('Bearer '):
                    return Response({
                        'code': 401,
                        'message': '缺少认证令牌'
                    }, status=status.HTTP_401_UNAUTHORIZED)
                
                from rest_framework_simplejwt.tokens import AccessToken
                token_str = auth_header.split(' ')[1]
                access_token = AccessToken(token_str)
                user_id = access_token['user_id']
                
                if isinstance(user_id, str):
                    user_id = int(user_id)
                
                user = SysUser.objects.get(id=user_id)

            # 获取上传的文件或base64数据
            if 'avatar' in request.FILES:
                # 处理文件上传
                avatar_file = request.FILES['avatar']
                
                # 验证文件类型
                if not avatar_file.content_type.startswith('image/'):
                    return Response({
                        'code': 400,
                        'message': '上传文件必须是图片格式'
                    }, status=status.HTTP_400_BAD_REQUEST)
                
                # 验证文件大小（2MB）
                if avatar_file.size > 2 * 1024 * 1024:
                    return Response({
                        'code': 400,
                        'message': '头像文件大小不能超过2MB'
                    }, status=status.HTTP_400_BAD_REQUEST)
                
                # 生成唯一文件名
                file_extension = os.path.splitext(avatar_file.name)[1]
                filename = f"avatar_{user.id}_{uuid.uuid4().hex[:8]}{file_extension}"
                
                # 保存文件
                file_path = default_storage.save(f"avatars/{filename}", avatar_file)
                avatar_url = default_storage.url(file_path)
                
            elif 'avatar_data' in request.data:
                # 处理base64数据
                avatar_data = request.data.get('avatar_data')
                
                # 解析base64数据
                if avatar_data.startswith('data:image/'):
                    # 提取base64数据部分
                    header, data = avatar_data.split(',', 1)
                    # 提取文件类型
                    content_type = header.split(';')[0].split(':')[1]
                    # 提取文件扩展名
                    if 'jpeg' in content_type:
                        file_extension = '.jpg'
                    elif 'png' in content_type:
                        file_extension = '.png'
                    elif 'gif' in content_type:
                        file_extension = '.gif'
                    else:
                        file_extension = '.jpg'  # 默认为jpg
                    
                    # 解码base64数据
                    try:
                        image_data = base64.b64decode(data)
                    except Exception:
                        return Response({
                            'code': 400,
                            'message': 'base64数据格式错误'
                        }, status=status.HTTP_400_BAD_REQUEST)
                    
                    # 验证文件大小（2MB）
                    if len(image_data) > 2 * 1024 * 1024:
                        return Response({
                            'code': 400,
                            'message': '头像文件大小不能超过2MB'
                        }, status=status.HTTP_400_BAD_REQUEST)
                    
                    # 生成唯一文件名
                    filename = f"avatar_{user.id}_{uuid.uuid4().hex[:8]}{file_extension}"
                    
                    # 保存文件
                    file_path = default_storage.save(f"avatars/{filename}", ContentFile(image_data))
                    avatar_url = default_storage.url(file_path)
                else:
                    return Response({
                        'code': 400,
                        'message': '不支持的数据格式'
                    }, status=status.HTTP_400_BAD_REQUEST)
            else:
                return Response({
                    'code': 400,
                    'message': '缺少头像数据'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 更新用户头像
            user.avatar = avatar_url
            user.save()
            
            return Response({
                'code': 200,
                'message': '头像上传成功',
                'data': {
                    'avatar': avatar_url
                }
            })
            
        except SysUser.DoesNotExist:
            return Response({
                'code': 401,
                'message': '用户不存在'
            }, status=status.HTTP_401_UNAUTHORIZED)
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'头像上传失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class UserProfileView(APIView):
    """
    用户个人信息视图类
    获取当前登录用户的详细信息，包括角色
    """
    permission_classes = [AllowAny]

    def get(self, request):
        """
        处理GET请求获取当前用户信息
        :param request: 请求对象
        :return: 用户信息和角色
        """
        try:
            # 获取当前用户ID
            current_user_id = None
            auth_header = request.META.get('HTTP_AUTHORIZATION')
            if auth_header and auth_header.startswith('Bearer '):
                try:
                    from rest_framework_simplejwt.tokens import AccessToken
                    token_str = auth_header.split(' ')[1]
                    access_token = AccessToken(token_str)
                    user_id = access_token['user_id']
                    if isinstance(user_id, str):
                        user_id = int(user_id)
                    current_user_id = user_id
                except Exception:
                    return Response({
                        'code': 401,
                        'message': '认证失败'
                    }, status=status.HTTP_401_UNAUTHORIZED)
            
            if not current_user_id:
                return Response({
                    'code': 401,
                    'message': '缺少认证令牌'
                }, status=status.HTTP_401_UNAUTHORIZED)
            
            # 获取用户信息和角色
            user_with_roles = get_user_with_roles(current_user_id)
            if not user_with_roles:
                return Response({
                    'code': 404,
                    'message': '用户不存在'
                }, status=status.HTTP_404_NOT_FOUND)
            
            return Response({
                'code': 200,
                'message': '获取用户信息成功',
                'data': user_with_roles
            })
            
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'获取用户信息失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class UserListView(APIView):
    """
    用户列表视图类
    处理用户列表查询请求，支持分页、搜索、状态筛选
    实现基于角色的数据访问控制
    """
    permission_classes = [AllowAny]

    def get(self, request):
        """
        处理GET请求获取用户列表
        :param request: 包含查询参数的请求
        :return: 用户列表数据
        """
        try:
            # 获取当前用户ID
            current_user_id = None
            auth_header = request.META.get('HTTP_AUTHORIZATION')
            if auth_header and auth_header.startswith('Bearer '):
                try:
                    from rest_framework_simplejwt.tokens import AccessToken
                    token_str = auth_header.split(' ')[1]
                    access_token = AccessToken(token_str)
                    user_id = access_token['user_id']
                    if isinstance(user_id, str):
                        user_id = int(user_id)
                    current_user_id = user_id
                except Exception:
                    return Response({
                        'code': 401,
                        'message': '认证失败'
                    }, status=status.HTTP_401_UNAUTHORIZED)
            
            if not current_user_id:
                return Response({
                    'code': 401,
                    'message': '缺少认证令牌'
                }, status=status.HTTP_401_UNAUTHORIZED)
            
            # 获取查询参数
            page = int(request.GET.get('page', 1))
            page_size = int(request.GET.get('page_size', 10))
            username = request.GET.get('username', '')
            email = request.GET.get('email', '')
            status_filter = request.GET.get('status', '')
            
            # 获取当前用户可访问的用户ID列表
            accessible_user_ids = get_accessible_users(current_user_id)
            
            # 构建查询条件
            query = Q(id__in=accessible_user_ids)
            
            if username:
                query &= Q(username__icontains=username)
            
            if email:
                query &= Q(email__icontains=email)
            
            if status_filter == 'active':
                query &= Q(status=0)
            elif status_filter == 'inactive':
                query &= Q(status=1)
            
            # 查询用户列表
            users = SysUser.objects.filter(query).order_by('-create_time')
            
            # 分页处理
            paginator = Paginator(users, page_size)
            try:
                current_page = paginator.page(page)
            except PageNotAnInteger:
                current_page = paginator.page(1)
            except EmptyPage:
                current_page = paginator.page(paginator.num_pages)
            
            # 构建返回数据，包含角色信息
            users_data = []
            for user in current_page:
                user_with_roles = get_user_with_roles(user.id)
                if user_with_roles:
                    users_data.append(user_with_roles)
            
            return Response({
                'code': 200,
                'message': '获取用户列表成功',
                'data': {
                    'results': users_data,
                    'count': paginator.count,
                    'page': page,
                    'page_size': page_size,
                    'total_pages': paginator.num_pages
                }
            })
            
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'获取用户列表失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class UserCreateView(APIView):
    """
    用户创建视图类
    处理新增用户请求
    实现基于角色的创建权限控制
    """
    permission_classes = [AllowAny]

    def post(self, request):
        """
        处理POST请求创建新用户
        :param request: 包含用户信息的请求
        :return: 创建结果
        """
        try:
            # 获取当前用户ID
            current_user_id = None
            auth_header = request.META.get('HTTP_AUTHORIZATION')
            if auth_header and auth_header.startswith('Bearer '):
                try:
                    from rest_framework_simplejwt.tokens import AccessToken
                    token_str = auth_header.split(' ')[1]
                    access_token = AccessToken(token_str)
                    user_id = access_token['user_id']
                    if isinstance(user_id, str):
                        user_id = int(user_id)
                    current_user_id = user_id
                except Exception:
                    return Response({
                        'code': 401,
                        'message': '认证失败'
                    }, status=status.HTTP_401_UNAUTHORIZED)
            
            if not current_user_id:
                return Response({
                    'code': 401,
                    'message': '缺少认证令牌'
                }, status=status.HTTP_401_UNAUTHORIZED)
            
            # 获取请求数据
            import json
            if hasattr(request, 'data'):
                data = request.data
            else:
                if request.content_type == 'application/json':
                    data = json.loads(request.body.decode('utf-8'))
                else:
                    data = request.POST
            
            username = data.get('username')
            email = data.get('email')
            first_name = data.get('first_name')
            password = data.get('password')
            is_active = data.get('is_active', True)
            role_name = data.get('role', '普通用户')  # 默认为普通用户
            
            # 检查是否有创建指定角色用户的权限
            if not can_create_user_with_role(current_user_id, role_name):
                return Response({
                    'code': 403,
                    'message': f'您没有权限创建{role_name}角色的用户'
                }, status=status.HTTP_403_FORBIDDEN)
            
            # 数据验证
            if not username:
                return Response({
                    'code': 400,
                    'message': '用户名不能为空'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            if not password:
                return Response({
                    'code': 400,
                    'message': '密码不能为空'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            if len(password) < 6:
                return Response({
                    'code': 400,
                    'message': '密码长度不能少于6位'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            if email and SysUser.objects.filter(email=email).exists():
                return Response({
                    'code': 400,
                    'message': '邮箱已存在'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 检查用户名是否已存在
            if SysUser.objects.filter(username=username).exists():
                return Response({
                    'code': 400,
                    'message': '用户名已存在'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 创建新用户
            user = SysUser.objects.create(
                username=username,
                password=make_password(password),
                email=email,
                nickname=first_name,  # 使用nickname存储first_name
                status=0 if is_active else 1
            )
            
            # 为用户分配角色
            from role.models import SysRole, SysUserRole
            try:
                role = SysRole.objects.get(name=role_name)
                SysUserRole.objects.create(user_id=user.id, role=role)
            except SysRole.DoesNotExist:
                # 如果角色不存在，默认分配普通用户角色
                try:
                    default_role = SysRole.objects.get(name='普通用户')
                    SysUserRole.objects.create(user_id=user.id, role=default_role)
                except SysRole.DoesNotExist:
                    pass
            
            return Response({
                'code': 200,
                'message': '用户创建成功',
                'data': {
                    'id': user.id,
                    'username': user.username,
                    'email': user.email,
                    'first_name': user.nickname,
                    'is_active': user.status == 0,
                    'role': role_name
                }
            })
            
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'用户创建失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class UserUpdateView(APIView):
    """
    用户更新视图类
    处理用户信息更新请求
    实现基于角色的更新权限控制
    """
    permission_classes = [AllowAny]

    def put(self, request, user_id):
        """
        处理PUT请求更新用户信息
        :param request: 包含用户信息的请求
        :param user_id: 用户ID
        :return: 更新结果
        """
        try:
            # 获取当前用户ID
            current_user_id = None
            auth_header = request.META.get('HTTP_AUTHORIZATION')
            if auth_header and auth_header.startswith('Bearer '):
                try:
                    from rest_framework_simplejwt.tokens import AccessToken
                    token_str = auth_header.split(' ')[1]
                    access_token = AccessToken(token_str)
                    operator_id = access_token['user_id']
                    if isinstance(operator_id, str):
                        operator_id = int(operator_id)
                    current_user_id = operator_id
                except Exception:
                    return Response({
                        'code': 401,
                        'message': '认证失败'
                    }, status=status.HTTP_401_UNAUTHORIZED)
            
            if not current_user_id:
                return Response({
                    'code': 401,
                    'message': '缺少认证令牌'
                }, status=status.HTTP_401_UNAUTHORIZED)
            
            # 检查是否有权限管理该用户
            if not can_manage_user(current_user_id, user_id):
                return Response({
                    'code': 403,
                    'message': '您没有权限管理该用户'
                }, status=status.HTTP_403_FORBIDDEN)
            
            # 获取用户对象
            user = SysUser.objects.get(id=user_id)
            
            # 获取请求数据
            import json
            if hasattr(request, 'data'):
                data = request.data
            else:
                if request.content_type == 'application/json':
                    data = json.loads(request.body.decode('utf-8'))
                else:
                    data = request.POST
            
            username = data.get('username')
            email = data.get('email')
            first_name = data.get('first_name')
            is_active = data.get('is_active')
            role = data.get('role')  # 新增角色字段
            
            # 数据验证
            if username and username != user.username:
                if SysUser.objects.filter(username=username).exists():
                    return Response({
                        'code': 400,
                        'message': '用户名已存在'
                    }, status=status.HTTP_400_BAD_REQUEST)
            
            if email and email != user.email:
                if SysUser.objects.filter(email=email).exists():
                    return Response({
                        'code': 400,
                        'message': '邮箱已存在'
                    }, status=status.HTTP_400_BAD_REQUEST)
            
            # 检查角色更新权限
            if role:
                if not can_create_user_with_role(current_user_id, role):
                    return Response({
                        'code': 403,
                        'message': f'您没有权限将用户角色设置为{role}'
                    }, status=status.HTTP_403_FORBIDDEN)
            
            # 更新用户信息
            if username:
                user.username = username
            if email:
                user.email = email
            if first_name:
                user.nickname = first_name
            if is_active is not None:
                user.status = 0 if is_active else 1
            
            user.save()
            
            # 更新用户角色（如果提供了角色信息）
            if role:
                # 先清除现有角色
                SysUserRole.objects.filter(user_id=user.id).delete()
                
                # 添加新角色
                try:
                    role_obj = SysRole.objects.get(name=role)
                    SysUserRole.objects.create(user_id=user.id, role=role_obj)
                except SysRole.DoesNotExist:
                    # 如果角色不存在，创建它
                    role_obj = SysRole.objects.create(name=role, description=f'{role}角色')
                    SysUserRole.objects.create(user_id=user.id, role=role_obj)
            
            # 获取更新后的用户角色
            user_roles = get_user_role_names(user.id)
            
            return Response({
                'code': 200,
                'message': '用户信息更新成功',
                'data': {
                    'id': user.id,
                    'username': user.username,
                    'email': user.email,
                    'first_name': user.nickname,
                    'is_active': user.status == 0,
                    'roles': user_roles,
                    'role_display': ', '.join(user_roles) if user_roles else '无角色'
                }
            })
            
        except SysUser.DoesNotExist:
            return Response({
                'code': 404,
                'message': '用户不存在'
            }, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'用户信息更新失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class UserToggleStatusView(APIView):
    """
    用户状态切换视图类
    处理用户状态切换请求（启用/禁用）
    实现基于角色的状态切换权限控制
    """
    permission_classes = [AllowAny]

    def patch(self, request, user_id):
        """
        处理PATCH请求切换用户状态
        :param request: 请求对象
        :param user_id: 用户ID
        :return: 切换结果
        """
        try:
            # 获取当前用户ID
            current_user_id = None
            auth_header = request.META.get('HTTP_AUTHORIZATION')
            if auth_header and auth_header.startswith('Bearer '):
                try:
                    from rest_framework_simplejwt.tokens import AccessToken
                    token_str = auth_header.split(' ')[1]
                    access_token = AccessToken(token_str)
                    operator_id = access_token['user_id']
                    if isinstance(operator_id, str):
                        operator_id = int(operator_id)
                    current_user_id = operator_id
                except Exception:
                    return Response({
                        'code': 401,
                        'message': '认证失败'
                    }, status=status.HTTP_401_UNAUTHORIZED)
            
            if not current_user_id:
                return Response({
                    'code': 401,
                    'message': '缺少认证令牌'
                }, status=status.HTTP_401_UNAUTHORIZED)
            
            # 检查是否有权限管理该用户
            if not can_manage_user(current_user_id, user_id):
                return Response({
                    'code': 403,
                    'message': '您没有权限管理该用户'
                }, status=status.HTTP_403_FORBIDDEN)
            
            # 获取用户对象
            user = SysUser.objects.get(id=user_id)
            
            # 切换用户状态
            user.status = 1 if user.status == 0 else 0
            user.save()
            
            status_text = '启用' if user.status == 0 else '禁用'
            
            return Response({
                'code': 200,
                'message': f'用户已{status_text}',
                'data': {
                    'id': user.id,
                    'username': user.username,
                    'is_active': user.status == 0,
                    'status': user.status
                }
            })
            
        except SysUser.DoesNotExist:
            return Response({
                'code': 404,
                'message': '用户不存在'
            }, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'状态切换失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class UserDeleteView(APIView):
    """
    用户删除视图类
    处理用户删除请求
    实现基于角色的删除权限控制
    """
    permission_classes = [AllowAny]

    def delete(self, request, user_id):
        """
        处理DELETE请求删除用户
        :param request: 请求对象
        :param user_id: 用户ID
        :return: 删除结果
        """
        try:
            # 获取当前用户ID
            current_user_id = None
            auth_header = request.META.get('HTTP_AUTHORIZATION')
            if auth_header and auth_header.startswith('Bearer '):
                try:
                    from rest_framework_simplejwt.tokens import AccessToken
                    token_str = auth_header.split(' ')[1]
                    access_token = AccessToken(token_str)
                    operator_id = access_token['user_id']
                    if isinstance(operator_id, str):
                        operator_id = int(operator_id)
                    current_user_id = operator_id
                except Exception:
                    return Response({
                        'code': 401,
                        'message': '认证失败'
                    }, status=status.HTTP_401_UNAUTHORIZED)
            
            if not current_user_id:
                return Response({
                    'code': 401,
                    'message': '缺少认证令牌'
                }, status=status.HTTP_401_UNAUTHORIZED)
            
            # 检查是否是试图删除自己
            if current_user_id == user_id:
                return Response({
                    'code': 403,
                    'message': '不能删除自己的账户'
                }, status=status.HTTP_403_FORBIDDEN)
            
            # 检查是否有权限管理该用户
            if not can_manage_user(current_user_id, user_id):
                return Response({
                    'code': 403,
                    'message': '您没有权限删除该用户'
                }, status=status.HTTP_403_FORBIDDEN)
            
            # 获取用户对象
            user = SysUser.objects.get(id=user_id)
            username = user.username
            
            # 检查目标用户的角色，确保不删除超级管理员（除了自己）
            target_roles = get_user_role_names(user_id)
            current_roles = get_user_role_names(current_user_id)
            
            # 超级管理员不能删除其他超级管理员
            if '超级管理员' in current_roles and '超级管理员' in target_roles:
                return Response({
                    'code': 403,
                    'message': '不能删除其他超级管理员'
                }, status=status.HTTP_403_FORBIDDEN)
            
            # 普通管理员只能删除普通用户
            if '普通管理员' in current_roles and '超级管理员' not in current_roles:
                if '超级管理员' in target_roles or '普通管理员' in target_roles:
                    return Response({
                        'code': 403,
                        'message': '您只能删除普通用户'
                    }, status=status.HTTP_403_FORBIDDEN)
            
            # 先删除用户角色关联
            SysUserRole.objects.filter(user_id=user.id).delete()
            
            # 删除用户
            user.delete()
            
            return Response({
                'code': 200,
                'message': f'用户 "{username}" 已成功删除'
            })
            
        except SysUser.DoesNotExist:
            return Response({
                'code': 404,
                'message': '用户不存在'
            }, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'用户删除失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
